package handle

import (
	"AcsGo/internal/domain"
	"AcsGo/internal/model"
	"database/sql"
	"time"
)

func HandleReaderRegister(str string) (string, error) {
	var jk string
	var ok string
	var rdbm string
	readerRegisterRequest, err := domain.ReaderRegister(str)
	if err != nil {
		return "", err
	}
	rdbm = readerRegisterRequest.PatronIdentifier.Value
	lg.Debugf("readerRegisterRequest: %v", readerRegisterRequest)

	db, err := model.ConnectDB()
	if err != nil {
		return "", err
	}

	_, err = model.GetReaderByBm(db, readerRegisterRequest.PatronIdentifier.Value)

	if err == nil {
		jk = ""
		ok = "0"
		queryResponse := domain.InitReaderRegisterReq(rdbm, ok, jk, "")
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("succes 读者存在: %v", sb)
		return sb, nil
	}

	// 插入reader表 密码默认123456
	name := readerRegisterRequest.PatronName.Value
	sfzh := readerRegisterRequest.IdCardNo.Value
	sex := readerRegisterRequest.Gender.Value
	pass := readerRegisterRequest.PatronPassword.Value
	if pass == "" {
		pass = ""
	}
	phone := readerRegisterRequest.Fixphone.Value
	unit := ""
	ltype := "01"
	address := ""
	now := time.Now()
	cdrq := now.Format("20060102")
	statues := "有效"
	startdt := now.Format("20060102")
	oneYearLater := now.AddDate(1, 0, 0) // Add 1 year, 0 months, and 0 days
	enddt := oneYearLater.Format("20060102")
	ptwjqk := "0"
	xyjs := 0
	admin := "tsg"
	adminrq := now.Format("20060102")

	reader := model.Reader{
		BM:      rdbm,
		Name:    name,
		SFZH:    sfzh,
		Sex:     sql.NullString{String: sex, Valid: true},
		Pass:    pass,
		Phone:   sql.NullString{String: phone, Valid: true},
		Unit:    sql.NullString{String: unit, Valid: true},
		LType:   ltype,
		Address: sql.NullString{String: address, Valid: true},
		CDRQ:    cdrq,
		Statues: statues,
		Startdt: startdt,
		Enddt:   enddt,
		Ptwjqk:  ptwjqk,
		Xyjs:    xyjs,
		Admin:   admin,
		Adminrq: adminrq,
	}
	err = model.CreateReader(db, &reader)
	if err != nil {
		lg.Errorf("CreateReader: %v", err)
		// return "", err
	}
	jk = "0"
	ok = "1"
	queryResponse := domain.InitReaderRegisterReq(rdbm, ok, jk, enddt)
	sb, _ := queryResponse.StringFormat()
	lg.Debugf("succes: %v", sb)
	return sb, nil
}
